﻿using System;
using System.Threading.Tasks;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using TiaoTaoHelper.Wtm.Models;
using HengTong.Model.Db.Hr;
using UUIDNext;


namespace HengTong.ViewModel.Person.SysPersonResumeVms
{
    public partial class SysPersonResumeVm : BaseCRUDVM<SysPersonResume>
    {
        public SysPersonResumeVm()
        {
            SetInclude(x => x.Person);
            SetInclude(x => x.TransferRequest);
            SetInclude(x => x.OriginalGroup);
            SetInclude(x => x.OriginalPosition);
            SetInclude(x => x.NewGroup);
            SetInclude(x => x.NewPosition);
        }

        protected override void InitVM()
        {
        }

        public override async Task DoAddAsync()
        {
            Entity.ID = Uuid.NewDatabaseFriendly(Database.SqlServer);
            Entity.ResumeType = "人事变动";
            if (Entity is IBasePoco poco)
            {
                poco.CreateBy = Wtm.LoginUserInfo?.ITCode;
                poco.UpdateBy = Wtm.LoginUserInfo?.ITCode;
                poco.CreateTime = DateTime.Now;
                poco.UpdateTime = DateTime.Now;
            }

            await base.DoAddAsync();
        }

        public override async Task DoEditAsync(bool updateAllFields = false)
        {
            if (Entity is IBasePoco poco)
            {
                poco.UpdateBy = Wtm.LoginUserInfo?.ITCode;
                poco.UpdateTime = DateTime.Now;
            }

            await base.DoEditAsync(updateAllFields);
        }

        public async Task ApproveAsync(bool upAllFields = false)
        {
            DC = Wtm.CreateDC();
            var transaction = DC.BeginTransaction();
            try
            {
                if (Entity is IFlow flow)
                {
                    flow.Approver = Wtm.LoginUserInfo?.ITCode;
                    flow.ApprovalTime = DateTime.Now;
                }

                await base.DoEditAsync(upAllFields);
                if (MSD.IsValid)
                {
                    await ContinueWorkflowAsync(ActionName, Remark);
                    await transaction.CommitAsync();
                }
                else
                {
                    await transaction.RollbackAsync();
                }
            }
            catch (Exception e)
            {
                // 回滚事务
                await transaction.RollbackAsync();
                MSD.AddModelError(" ", $"审批操作异常: {e.Message}");
            }
            finally
            {
                await transaction.DisposeAsync();
            }
        }

        public override void DoDelete()
        {
            base.DoDelete();
        }
    }
}